package com.stylefeng.guns.modular.yjya.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.dao.AccidentProcessMapper;
import com.stylefeng.guns.common.persistence.model.AccidentProcess;
import com.stylefeng.guns.common.persistence.model.AccidentType;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.yjya.dao.AccidentProcessDao;
import com.stylefeng.guns.modular.yjya.service.IAccidentProcessService;
import com.stylefeng.guns.modular.yjya.service.IAccidentTypeService;
import com.stylefeng.guns.modular.yjya.warpper.AccidentProcessWarpper;
import com.stylefeng.guns.modular.yjya.warpper.AccidentWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 事故处理措施控制器
 *
 * @author 殷佳成
 * @Date 2018-01-17 14:01:04
 */
@Controller
@RequestMapping("/accidentProcess")
public class AccidentProcessController extends BaseController {

    private String PREFIX = "/yjya/accidentProcess/";

    @Autowired
    private IAccidentProcessService accidentProcessService;
    @Autowired
    private IAccidentTypeService iAccidentTypeService;
    @Autowired
    private AccidentProcessMapper accidentProcessMapper;

    @Autowired
    private IAccidentTypeService accidentTypeService;


    @Autowired
    private AccidentProcessDao accidentProcessDao;


    /**
     * 跳转到事故处理措施首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "accidentProcess.html";
    }

    /**
     * 跳转到添加事故处理措施
     */
    @RequestMapping("/accidentProcess_add")
    public String accidentProcessAdd() {
        return PREFIX + "accidentProcess_add.html";
    }

    /**
     * 跳转到修改事故处理措施
     */
    @RequestMapping("/accidentProcess_update/{accidentProcessId}")
    public String accidentProcessUpdate(@PathVariable Integer accidentProcessId, Model model) {
        AccidentProcess accidentProcess = accidentProcessService.selectById(accidentProcessId);

        model.addAttribute("item", accidentProcess);

        String typeName=" ";
        if(accidentProcess.getTypeId() == 0){
            typeName="顶级";

        }else{
            typeName = iAccidentTypeService.selectById(accidentProcess.getTypeId()).getName();
        }
        model.addAttribute("typeName" ,typeName);
        LogObjectHolder.me().set(accidentProcess);
        return PREFIX + "accidentProcess_edit.html";
    }

    @RequestMapping("/accidentProcess_sel/{accidentProcessTypeId}")
    @ResponseBody
    public Object sel(@PathVariable("accidentProcessTypeId") Integer accidentProcessTypeId, Model model) {
        Wrapper wrapper = new EntityWrapper<AccidentProcess>();
        wrapper.eq("type_id", accidentProcessTypeId);
        List<Map<String, Object>> mapList = accidentProcessService.selectMaps(wrapper);
        return new AccidentWarpper(mapList).warp();
    }

    /**
     * 获取事故处理措施列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "main", required = false) String main,
                       @RequestParam(value = "typeId", required = false) Integer typeId) {
          Page<AccidentProcess> page = new PageFactory<AccidentProcess>().defaultPage();
          List<Map<String,Object>> mapList = accidentProcessMapper.selectProcesses(page,null,typeId);
          page.setRecords((List<AccidentProcess>) new AccidentProcessWarpper(mapList).warp());
          return super.packForBT(page);

    }

    /**
     * 新增事故处理措施
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(AccidentProcess accidentProcess) {
        accidentProcessService.insert(accidentProcess);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除事故处理措施
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") List<Integer> ids) {
        accidentProcessService.deleteBatchIds(ids);
        return SUCCESS_TIP;
    }

    /**
     * 修改事故处理措施
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(AccidentProcess accidentProcess) {
        accidentProcessService.updateById(accidentProcess);
        return super.SUCCESS_TIP;
    }

    /**
     * 事故处理措施详情
     */
    @RequestMapping(value = "/detail/{accidentProcessId}")
    @ResponseBody
    public Object detail(@PathVariable("accidentProcessId") Integer accidentProcessId) {
        return accidentProcessService.selectById(accidentProcessId);
    }

    @RequestMapping(value = "/string/{accidentProcessId}")
    @ResponseBody
    public Object getString(@PathVariable("accidentProcessId") Integer accidentProcessId) {
        AccidentProcess accidentProcess = accidentProcessService.selectById(accidentProcessId);
        accidentProcess.setMain(accidentProcess.getMain());
        return accidentProcess.toString();
    }

    @RequestMapping(value = "/mainAction/{accidentProcessId}")
    @ResponseBody
    public Object getmainAction(@PathVariable("accidentProcessId") Integer accidentProcessId) {

        AccidentProcess accidentProcess = accidentProcessService.selectById(accidentProcessId);
        accidentProcess.setMain(accidentProcess.getMain());
        return accidentProcess;
    }

    /**
     导出Excel模板
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response
            , ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "事故处置措施");
        modelMap.put(NormalExcelConstants.CLASS, AccidentProcess.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("事故处置措施列表", "导出人:" + ShiroKit.getUser().getName()+"           注：分组示例（火灾场景-车站-设备区）",
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }

    @RequestMapping(method = RequestMethod.POST,path = "/importExcel")
    @ResponseBody
    public String importExcel(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse response)throws Exception{
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        for(Map.Entry<String,MultipartFile> entity : fileMap.entrySet()){
            MultipartFile multipartFile = entity.getValue(); //获取上传文件对象
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(2);
            importParams.setHeadRows(1);
            importParams.setNeedSave(true);
            List <AccidentProcess> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(),AccidentProcess.class,importParams);
            List<AccidentType> listAccidentType = accidentTypeService.selectList(null);
            for(int i = 0;i<list.size();i++){
                for(int j = 0;j<listAccidentType.size();j++){
                    if(list.get(i).getTypeName().equals(listAccidentType.get(j).getAllName())){
                        list.get(i).setTypeId(listAccidentType.get(j).getId());
                    }
                }
            }
            accidentProcessService.insertBatch(list);
            multipartFile.getInputStream().close();

        }
        return "文件导入成功";
    }

}
